<?php

namespace App\Http\Controllers\Api\v1;

use App\Http\Controllers\Common\ApiHelper;
use App\Http\Controllers\Common\AppController;
use App\Models\Api\v1\Message;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use GatewayWorker\Lib\Gateway;
use Illuminate\Http\Request;

class ImController extends AppController
{
    //发送消息
    public function sendMessage(Request $request)
    {
        $fid = $request->get('fid');
        $data = $request->get('data');
        if (empty($data)) return ApiHelper::responseError([], '不能发送空消息');
        $content = json_encode($data);
        if (!Gateway::getClientIdByUid($fid)) {
            return ApiHelper::responseError([], '当前用户在线');
        }
        Gateway::sendToUid($fid, $content);
        //储存聊天记录
        Message::createMessage($data, $fid);
        return ApiHelper::responseSuccess([], '发送成功');
    }

    public function messageList(Request $request)
    {
        $param = $request->all();
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 20;
        $data = Message::query()->where(['uid' => auth('api')->id(), 'fid' => $param['fid']])->orderByDesc('create_time')->paginate($limit);
        return ApiHelper::responseSuccess($data, '获取成功');
    }

    //登录
    public function login(Request $request)
    {
        $username = $request->get('username');
        $user = User::query()->where('username', $username)->first();
        if (!$user) {
            //创建用户
            DB::beginTransaction();
            try {
                $user = User::query()->create([
                    'username' => $username
                ]);
                DB::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
                Log::info('创建用户-失败', ['data' => $exception->getMessage()]);
                return ApiHelper::responseError('注册失败,请稍后再试');
            }
        }
        $token = auth('api')->login($user);
        $data = [
            'access_token' => 'Bearer ' . $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60,
        ];
        return ApiHelper::responseSuccess($data, '登录成功');
    }

    public function userInfo()
    {
        $info = auth('api')->user();
        return ApiHelper::responseSuccess($info, '成功');
    }

    public function bandUser(Request $request)
    {
        $client_id = $request->get('client_id');
        if (empty($client_id)) return ApiHelper::responseError([], '绑定失败');
        Gateway::bindUid($client_id, auth('api')->id());
        return ApiHelper::responseSuccess([], '绑定成功');
    }

    //查询UID是否在线
    public function isUidOnline(Request $request)
    {
        $isUidOnline = Gateway::getClientIdByUid($request->get('uid'));
        if (!$isUidOnline) return ApiHelper::responseError([], '不在线');
        return ApiHelper::responseSuccess($isUidOnline, '在线');
    }

}
